import axios from "axios";
import { config } from "process";
import qs from "querystring";
import { Toast } from "antd-mobile";
import store from "../store"
import {getInfo} from "../store/moudules/login"

//请求拦截
axios.interceptors.request.use((config) => {
  if (config.url !== "/api/login" && config.url !== "/api/register") {
    //取出仓库的info
    config.headers.authorization = getInfo(store.getState()).token;
  }
  return config;
});
//响应拦截
axios.interceptors.response.use((res) => {
  console.group("本次请求地址:" + res.config.url);
  console.log(res);
  console.groupEnd();
  if (res.data.code !== 200) {
    Toast.fail(res.data.msg, 1);
  }
  return res;
});

export function get(url, params = {}) {
  return axios({
    url,
    params,
  });
}

export function post(url, params = {}, isFile = false) {
  let data = null;
  if (isFile) {
    data = new FormData();
    Object.keys(params).forEach((key) => {
      data.append(key, params[key]);
    });
  } else {
    data = qs.stringify(params);
  }
  return axios({
    url,
    data,
    method: "post",
  });
}
